import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import {
  Card,
  Table,
  Button,
  Space,
  Badge,
  Typography,
  Tag,
  Message,
  Grid,
  Statistic,
  Progress,
  Descriptions,
} from '@arco-design/web-react'
import {
  IconLeft,
  IconRefresh,
  IconEye,
  IconStop,
  IconSync,
} from '@arco-design/web-react/icon'
import {
  getInstance,
  getInstanceTasks,
  getInstanceStatistics,
  cancelTask,
  retryTask,
} from '@/api/task'
import { TaskStatus } from '@/types/enums'
import { signalRService, HubEvent, type TaskStatusData } from '@/utils/websocket'
import type { PipelineInstance, TaskEntity, InstanceStatistics } from '@/types'
import LogViewerModal from '@/components/LogViewerModal'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import './index.css'

dayjs.extend(duration)

const { Title, Text } = Typography
const { Row, Col } = Grid

// 状态映射
const statusMap: Record<number, { text: string; color: string; status: any }> = {
  0: { text: '等待中', color: 'gray', status: 'default' },
  1: { text: '运行中', color: 'blue', status: 'processing' },
  2: { text: '成功', color: 'green', status: 'success' },
  3: { text: '失败', color: 'red', status: 'error' },
  4: { text: '已取消', color: 'orange', status: 'warning' },
}

export default function TaskDetailPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const [loading, setLoading] = useState(false)
  const [instance, setInstance] = useState<PipelineInstance | null>(null)
  const [tasks, setTasks] = useState<TaskEntity[]>([])
  const [statistics, setStatistics] = useState<InstanceStatistics | null>(null)
  const [logViewerVisible, setLogViewerVisible] = useState(false)
  const [selectedTask, setSelectedTask] = useState<{ id: number; name: string } | null>(null)
  const [isRealtimeConnected, setIsRealtimeConnected] = useState(false)

  // 加载实例详情
  const loadInstance = async () => {
    if (!id) return
    try {
      const data = await getInstance(Number(id))
      setInstance(data)
    } catch (error) {
      console.error('Failed to load instance:', error)
      Message.error('加载实例信息失败')
    }
  }

  // 加载任务列表
  const loadTasks = async () => {
    if (!id) return
    setLoading(true)
    try {
      const data = await getInstanceTasks(Number(id))
      setTasks(data)
    } catch (error) {
      console.error('Failed to load tasks:', error)
    } finally {
      setLoading(false)
    }
  }

  // 加载统计信息
  const loadStatistics = async () => {
    if (!id) return
    try {
      const data = await getInstanceStatistics(Number(id))
      setStatistics(data)
    } catch (error) {
      console.error('Failed to load statistics:', error)
    }
  }

  // 加载所有数据
  const loadAll = () => {
    loadInstance()
    loadTasks()
    loadStatistics()
  }

  useEffect(() => {
    loadAll()

    const instanceId = Number(id)
    if (!instanceId) return

    // 尝试建立 SignalR 连接并订阅实时状态
    const connectSignalR = async () => {
      try {
        if (!signalRService.isConnected()) {
          await signalRService.connect()
        }
        await signalRService.subscribePipelineInstance(instanceId)
        setIsRealtimeConnected(true)
      } catch (error) {
        console.warn('Failed to connect SignalR, falling back to polling:', error)
        setIsRealtimeConnected(false)
      }
    }

    connectSignalR()

    // SignalR 实时状态更新回调
    const handleStatusUpdate = (data: TaskStatusData) => {
      if (data.pipelineInstanceId === instanceId) {
        // 更新任务状态
        setTasks((prevTasks) =>
          prevTasks.map((task) =>
            task.taskId === data.taskId
              ? { ...task, status: data.status as TaskStatus }
              : task
          )
        )
        // 重新加载统计信息
        loadStatistics()
        loadInstance()
      }
    }

    signalRService.on(HubEvent.RECEIVE_TASK_STATUS, handleStatusUpdate)

    // 如果实例正在运行，使用轮询作为备选方案
    let timer: number | undefined
    if (instance?.status === 1) {
      timer = setInterval(loadAll, 5000)
    }

    return () => {
      if (timer) clearInterval(timer)
      signalRService.off(HubEvent.RECEIVE_TASK_STATUS, handleStatusUpdate)
      signalRService.unsubscribePipelineInstance(instanceId).catch(console.error)
    }
  }, [id, instance?.status])

  // 取消任务
  const handleCancelTask = async (taskId: number) => {
    try {
      await cancelTask(taskId)
      Message.success('已取消任务')
      loadAll()
    } catch (error) {
      console.error('Failed to cancel task:', error)
    }
  }

  // 重试任务
  const handleRetryTask = async (taskId: number) => {
    try {
      await retryTask(taskId)
      Message.success('任务已重新执行')
      loadAll()
    } catch (error) {
      console.error('Failed to retry task:', error)
    }
  }

  // 计算执行时长
  const getDuration = (startTime: string, endTime?: string) => {
    const start = dayjs(startTime)
    const end = endTime ? dayjs(endTime) : dayjs()
    const diff = end.diff(start)
    const dur = dayjs.duration(diff)

    const hours = Math.floor(dur.asHours())
    const minutes = dur.minutes()
    const seconds = dur.seconds()

    if (hours > 0) {
      return `${hours}h ${minutes}m ${seconds}s`
    } else if (minutes > 0) {
      return `${minutes}m ${seconds}s`
    } else {
      return `${seconds}s`
    }
  }

  const columns = [
    {
      title: '步骤名称',
      dataIndex: 'stepName',
      key: 'stepName',
      render: (name: string) => <strong>{name}</strong>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: number) => {
        const config = statusMap[status] || statusMap[0]
        return <Badge status={config.status} text={config.text} />
      },
    },
    {
      title: '执行节点',
      dataIndex: 'nodeName',
      key: 'nodeName',
      width: 150,
      render: (name: string, record: TaskEntity) => (
        <Tag color="arcoblue">{name || record.nodeId || '-'}</Tag>
      ),
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 180,
      render: (time: string) =>
        time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-',
    },
    {
      title: '执行时长',
      key: 'duration',
      width: 120,
      render: (_: any, record: TaskEntity) =>
        record.startTime ? getDuration(record.startTime, record.endTime) : '-',
    },
    {
      title: '重试次数',
      dataIndex: 'retryCount',
      key: 'retryCount',
      width: 100,
      render: (count: number) => count || 0,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: any, record: TaskEntity) => (
        <Space>
          <Button
            type="text"
            size="small"
            icon={<IconEye />}
            onClick={() => {
              setSelectedTask({ id: record.taskId, name: record.stepName })
              setLogViewerVisible(true)
            }}
          >
            日志
          </Button>
          {record.status === 3 && (
            <Button
              type="text"
              size="small"
              icon={<IconSync />}
              onClick={() => handleRetryTask(record.taskId)}
            >
              重试
            </Button>
          )}
          {record.status === 1 && (
            <Button
              type="text"
              size="small"
              status="danger"
              icon={<IconStop />}
              onClick={() => handleCancelTask(record.taskId)}
            >
              取消
            </Button>
          )}
        </Space>
      ),
    },
  ]

  if (!instance) {
    return (
      <div className="task-detail-page">
        <Card loading>
          <div style={{ height: 400 }} />
        </Card>
      </div>
    )
  }

  const statusConfig = statusMap[instance.status] || statusMap[0]

  return (
    <div className="task-detail-page">
      <div className="task-detail-header">
        <Space>
          <Button
            type="text"
            icon={<IconLeft />}
            onClick={() => navigate('/task')}
          >
            返回
          </Button>
          <Title heading={4} style={{ margin: 0 }}>
            任务详情 #{instance.id}
          </Title>
          {isRealtimeConnected && (
            <Badge status="success" text="实时更新" />
          )}
        </Space>
        <Button
          type="primary"
          icon={<IconRefresh />}
          onClick={loadAll}
          loading={loading}
        >
          刷新
        </Button>
      </div>

      {/* 实例信息卡片 */}
      <Card title="实例信息" style={{ marginBottom: 16 }}>
        <Descriptions
          column={3}
          data={[
            {
              label: '流水线',
              value: (
                <Typography.Text bold>{instance.pipeline?.name || `ID: ${instance.pipelineId}`}</Typography.Text>
              ),
            },
            {
              label: '状态',
              value: <Badge status={statusConfig.status} text={statusConfig.text} />,
            },
            {
              label: '触发人',
              value: instance.triggeredBy,
            },
            {
              label: '提交哈希',
              value: (
                <Tag style={{ fontFamily: 'monospace' }}>
                  {instance.commitHash?.substring(0, 8)}
                </Tag>
              ),
            },
            {
              label: '提交信息',
              value: instance.commitMessage,
            },
            {
              label: '提交作者',
              value: instance.commitAuthor || '-',
            },
            {
              label: '开始时间',
              value: dayjs(instance.startTime).format('YYYY-MM-DD HH:mm:ss'),
            },
            {
              label: '结束时间',
              value: instance.endTime
                ? dayjs(instance.endTime).format('YYYY-MM-DD HH:mm:ss')
                : '-',
            },
            {
              label: '执行时长',
              value: getDuration(instance.startTime, instance.endTime),
            },
          ]}
        />
      </Card>

      {/* 统计信息 */}
      {statistics && (
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总任务数"
                value={statistics.totalTasks}
                groupSeparator
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="成功"
                value={statistics.successTasks}
                groupSeparator
                style={{ color: 'rgb(var(--green-6))' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="失败"
                value={statistics.failedTasks}
                groupSeparator
                style={{ color: 'rgb(var(--red-6))' }}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="运行中"
                value={statistics.runningTasks}
                groupSeparator
                style={{ color: 'rgb(var(--blue-6))' }}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 进度条 */}
      {statistics && (
        <Card style={{ marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>
            <Text>执行进度</Text>
          </div>
          <Progress
            percent={statistics.progress}
            status={
              instance.status === 2
                ? 'success'
                : instance.status === 3
                ? 'error'
                : undefined
            }
          />
          {statistics.estimatedEndTime && instance.status === 1 && (
            <Text type="secondary" style={{ fontSize: 12, marginTop: 8 }}>
              预计完成时间：
              {dayjs(statistics.estimatedEndTime).format('YYYY-MM-DD HH:mm:ss')}
            </Text>
          )}
        </Card>
      )}

      {/* 任务列表 */}
      <Card title="任务列表">
        <Table
          columns={columns}
          data={tasks}
          loading={loading}
          pagination={false}
          rowKey="taskId"
          noDataElement={
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <Text type="secondary">暂无任务数据</Text>
            </div>
          }
        />
      </Card>

      {/* 日志查看器 */}
      <LogViewerModal
        visible={logViewerVisible}
        taskId={selectedTask?.id || null}
        taskName={selectedTask?.name}
        onCancel={() => {
          setLogViewerVisible(false)
          setSelectedTask(null)
        }}
      />
    </div>
  )
}
